package top.broncho.lottery.api

import android.content.Context
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Interceptor.Companion.invoke
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import top.broncho.lottery.BuildConfig
import top.broncho.lottery.util.hasInternet
import java.io.File
import java.util.concurrent.TimeUnit


private const val READ_TIMEOUT = 20L//读取超时时间,单位  秒
private const val WRITE_TIMEOUT = 20L//读取超时时间,单位  秒
private const val CONN_TIMEOUT = 10L//连接超时时间,单位  秒

private const val CACHE_DIR = "retrofit_manager_disk_cache"

private fun Context.provideCacheDir(): File {
    return externalCacheDir.takeIf { it != null } ?: cacheDir
}

private fun Context.provideCache(): Cache {
    return Cache(File(provideCacheDir(), CACHE_DIR), 1024 * 1024 * 50)
}

private fun Context.provideOkHttpClient(): OkHttpClient {
    //打印请求log
    val logging = HttpLoggingInterceptor().apply {
        level =
            if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
            else HttpLoggingInterceptor.Level.NONE
    }
    return OkHttpClient.Builder()
        .addNetworkInterceptor(provideNetCacheInterceptor())
        .addInterceptor(provideOfflineCacheInterceptor())
        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
        .connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)
        .cache(provideCache())
        .addInterceptor(logging)
        .build()//初始化一个client,不然retrofit会自己默认添加一个
}

private fun Context.provideOfflineCacheInterceptor(): Interceptor {
    return invoke { chain ->
        var request = chain.request()
        if (!hasInternet()) {
            val offlineCacheTime = 1 //离线的时候的缓存的过期时间
            request = request.newBuilder()
                .cacheControl(
                    CacheControl
                        .Builder()
                        .maxStale(offlineCacheTime, TimeUnit.DAYS)
                        .onlyIfCached()
                        .build()
                )
                .build()
        }
        chain.proceed(request)
    }
}

private fun provideNetCacheInterceptor(): Interceptor {
    return invoke { chain ->
        val request = chain.request()
        val response = chain.proceed(request)
        val onlineCacheTime = 60 * 60 * 24 //在线的时候的缓存过期时间，如果想要不缓存，直接时间设置为0
        response.newBuilder()
            .header("Cache-Control", "public, max-age=$onlineCacheTime")
            .removeHeader("Pragma")
            .build()
    }
}

fun Context.provideRetrofit(): Retrofit {
    val client = provideOkHttpClient()
    return Retrofit.Builder().client(client)
        .baseUrl(BuildConfig.BASE_URL_DEFAULT)
        .callFactory(CallFactoryProxy(client))
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}
